

const koa = require('koa')
const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const jweAuth = require('koa-jwt')
//秘钥
const secret = "it's a secret jjk"

//跨域问题
const cors = require('koa2-cors')
const koaBody = require("koa-body");
const static = require('koa-static')

const db = require("./lib/db");
const { getDB } = require('./lib/db');

db.initDB();

const fs = require("fs");
const path = require("path");

//去除密码再返回 
const { resetData } = require('./lib/resetData.js')




const app = new koa()
app.keys = ['some secret']
app.use(static(__dirname + '/'))
app.use(
    koaBody({
        multipart: true
    })
);
//跨域
app.use(cors({
    origin: '*',
    allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS', 'PUT'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Requested-With', 'Content-Length']
}))




// // 中间件对token进行验证
app.use(async (ctx, next) => {
    return next().catch((err) => {
        if (err.status === 401) {
            ctx.status = 401;
            console.log(err.message)
            ctx.body = {
                code: 20000,
                msg: '登录状态失效'
            }
        } else {
            throw err;
        }
    })
});

app.use(jweAuth({ secret }).unless({ path: [/^\/checkname/, /^\/users/, /^\/login/] }))


//名字是否被注册
router.get('/checkname/:username?', async ctx => {
    const username = ctx.request.params.username
    const [row] = await getDB().execute(`SELECT * FROM userlist WHERE username=? limit 1`, [username])
    if (row.length === 1) {
        ctx.body = {
            message: '该用户名已被注册',
            state: 201
        }
    }
    else {
        ctx.body = {
            message: '该用户名可用',
            state: 200
        }
    }


})
//添加用户
router.post('/users',
    async ctx => {
        res = ctx.request.body
        const sql = `INSERT INTO userlist (username,password) VALUES  (?,?)`;
        const [rows] = await getDB().execute(sql, [res.username, res.password]);
        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = {
                message: "添加成功",
                state: 200

            }

        } else {
            ctx.body = {
                message: "添加失败",
                state: 201
            }
        }
    })


//登录
router.post("/login", async ctx => {
    const { body } = ctx.request
    const { username, password } = body
    const [row] = await getDB().execute(`SELECT * FROM userlist WHERE username=? limit 1`, [username])
    if (row.length) {
        console.log(row);
        if (row[0].password === password) {
            console.log(username);
            ctx.body = {
                message: "登录成功",
                state: 200,
                user: username,
                Uid: row[0].id,
                //生成token，返回给客户端
                token: jwt.sign({
                    data: username,
                    //设置过期时间，单位为秒
                }, secret)

            }

        } else {
            ctx.body = {
                message: "登录失败",
                state: 201,

            }
        }

    } else {

        ctx.body = {
            message: "登录失败,用户名不存在",
            state: 201,

        }
    }
})
//获取用户信息
router.get('/userinfo',
    // jweAuth({ secret }),
    async ctx => {
        const [row] = await getDB().execute(`SELECT * FROM userlist WHERE id=? `, [ctx.query.uid])
        ctx.body = {
            state: 200,
            data: resetData(row)
        }


    })
//头像上传
router.post('/userinfo/upload/:id',
    async ctx => {
        const id = ctx.request.params.id
        const { img } = ctx.request.files;
        //保存到本地
        const uploadPath = '/upload/' + Date.now() + "_" + img.name
        saveImg(img, uploadPath)
        const url = 'http://localhost:8084' + uploadPath
        const sql = `update  userlist set PortraitUrl=? WHERE id=?`
        const [rows] = await getDB().execute(sql, [url, id])
        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = {
                message: "上传成功",
                state: 200
            }
        } else {
            ctx.body = {
                message: "上次失败",
                state: 201
            }

        }

    })


router.post("/complaint",
    // jweAuth({ secret }),
    async ctx => {
        const res = ctx.request.body
        const sql = `INSERT INTO complaintList (itemId,Ctext,username) VALUES  (?,?,?)`;
        const [rows] = await getDB().execute(sql, [res.itemId, res.text, res.userinfo]);
        if (rows.affectedRows === 1) {
            ctx.body = {
                message: "添加成功",
                state: 200
            }



        } else {
            ctx.body = {
                message: "添加失败",
                state: 201
            }
        }


    })


//客户端请求题目
router.get('/getitem',
    // jweAuth({ secret }),
    async ctx => {
        console.log(ctx.query.type);
        const [row] = await getDB().execute(`SELECT * FROM exercises WHERE source=? `, [ctx.query.type])


        // 随机输出数组中的某个元素
        const randomSelect = arr => arr[Math.floor(Math.random() * arr.length)];
        const res = randomSelect(row)
        ctx.body = { data: res, state: 200 }

    })
//收藏题目

router.post("/collect",
    // jweAuth({ secret }),
    async ctx => {

        const req = ctx.request.body

        const sql = `SELECT * FROM userlist WHERE username=? limit 1`
        const res = await getDB().execute(sql, [req.userinfo]);


        if (!res[0][0].collect) {
            console.log(res[0][0].collect);
            console.log(2);
            const sql1 = `update userlist set collect=? WHERE username=?`

            const [rows] = await getDB().execute(sql1, [req.id, req.userinfo]);
            if (rows.affectedRows === 1) {
                ctx.body = {
                    message: "收藏成功",
                    state: 200

                }

            } else {
                ctx.body = {
                    message: "收藏失败",
                    state: 201
                }
            }
        } else {
            console.log(1);
            const arr = res[0][0].collect.split(',')
            const check = String(req.id)
            var isUnique = true
            arr.map(item => {
                if (item === check) {
                    return isUnique = false
                }
            })

            if (isUnique) {
                console.log(req.id, arr);
                arr.push(req.id)
                const sql = `update userlist set collect=? WHERE username=?`

                const [rows] = await getDB().execute(sql, [String(arr), req.userinfo]);
                if (rows.affectedRows === 1) {
                    ctx.body = {
                        message: "收藏成功",
                        state: 200

                    }

                } else {
                    ctx.body = {
                        message: "收藏失败",
                        state: 201
                    }
                }
            } else {
                ctx.body = {
                    message: "已经收藏过了",
                    state: 304
                }
            }

        }


    })
router.get('/exercises',
    // jweAuth({ secret }),
    async ctx => {
        console.log(ctx.query.username);
        const sql = `SELECT * FROM userlist WHERE username=? limit 1`
        const res = await getDB().execute(sql, [ctx.query.username]);



        const sql1 = `SELECT * FROM exercises WHERE id in (${res[0][0].collect}) `
        const [rows] = await getDB().execute(sql1);

        ctx.body = {
            data: rows,
            state: 200,
            total: rows.length
        }
    })


router.delete('/exercises',
    // jweAuth({ secret }),
    async ctx => {
        console.log(ctx.query.username, ctx.query.id);
        const sql = `SELECT * FROM userlist WHERE username=? limit 1`
        const res = await getDB().execute(sql, [ctx.query.username]);
        const arr = res[0][0].collect.split(',')
        console.log(arr, 'arr');
        const req = String(ctx.query.id)
        const arr1 = arr.filter(item => item !== req)
        console.log(arr1, 'arr1');

        const sql1 = `update userlist set collect=? WHERE username=?`

        const [rows] = await getDB().execute(sql1, [String(arr1), ctx.query.username]);
        if (rows.affectedRows === 1) {
            ctx.body = {
                message: "取消收藏成功",
                state: 200

            }

        } else {
            ctx.body = {
                message: "取消收藏失败",
                state: 201
            }
        }
    })

    router.post('/userinfo/lifeTalk',
    // jweAuth({ secret }),
    async ctx => {
       
        const sql1 = `update userlist set lifeTalk=? WHERE id=?`
        console.log(ctx.request.body);
        const [rows] = await getDB().execute(sql1, [String(ctx.request.body.lifeTalk), ctx.request.body.uid]);
        if (rows.affectedRows === 1) {
            ctx.body = {
                state: 200

            }

        } else {
            ctx.body = {
                state: 201
            }
        }
    })
    function saveImg(img, uploadPath) {
        const readStream = fs.createReadStream(img.path);
        const savePath = path.join(__dirname, uploadPath);
        const writeStream = fs.createWriteStream(savePath);
        readStream.pipe(writeStream);
    }

app.use(router.routes())
app.listen(8084, () => { console.log('serve built') })